import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 使用json进行前后端交互
 */

/*
请求body格式：
    POST /json
    Content-Type: application/json

    {
       username: "Hikari"
       password: "123"
    }

响应body格式：
    {
       ok: true
    }
*/

class Request {
    public String username;
    public String password;
}
class Response {
    public boolean ok;
}
@WebServlet("/json")
public class JsonParameterServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        //需要在pom.xml中导入第三方库jackson

        ObjectMapper objectMapper = new ObjectMapper();//对象映射器，需要引入jackson依赖
        //ObjectMapper工作过程：读取流对象，将其中的json解析成Map对象，再把Map对象转换成对应Java对象（由反射确定），
        //具体来说，是将Request对象的每个属性,到Map中匹配key，匹配到了，赋成val，
        //另外，jackson只处理public属性和getter&setter
        Request request = objectMapper.readValue(req.getInputStream(), Request.class);

        System.out.println("username: " + request.username);
        System.out.println("password: " + request.password);

        Response response = new Response();
        response.ok = true;

        //根据传入的对象，拿到类对象，通过反射得到其中的属性和值，再构造成json格式的字符串
        String respJson = objectMapper.writeValueAsString(response);//把Java对象转换成json对象

        resp.setContentType("application/json; charset=utf8");
        resp.getWriter().write(respJson);//返回响应
    }
}

